﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using SurfaceAd.SDK.WP;
using WCYCReader.Main;
using WCYCReader.Main.Core;
using WCYCReader.Models;
using WCYCReader.Resources;
using WCYCReader.UserControls;
using WCYCReader.Utility;
using WCYCReader.ViewModels;

namespace WCYCReader
{
    public partial class IndexPage : PhoneApplicationPage
    {

        public HelpControl hc = new HelpControl();
        public DispatcherTimer downloadUpdateTime = new DispatcherTimer();
        public bool downloadUpdateTimeBegin;
        private BookList_M TodayRecommended_M = new BookList_M();
        private bool menuChanged;

        public IndexPage()
        {
            this.InitializeComponent();
            //this.AddHeaderToPivotItem();
            //
            if ((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"] != Visibility.Visible)
            {
                SolidColorBrush solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
                Application.Current.Resources.Add("PhoneBackgroundBrush", solidColorBrush);
            }
            if (SettingHelper.IsSettings("BookReader_Default"))
            {
                App.ReaderPage_Night = (bool)SettingHelper.GetValueFromSettings("BookReader_NightMode");
            }
            else
            {
                SettingHelper.SaveInToSettings("BookReader_Default", true);
                SettingHelper.SaveInToSettings("BookReader_fontSize", 26);
                SettingHelper.SaveInToSettings("BookReader_BackgroundNum", 0);
                SettingHelper.SaveInToSettings("ReaderPage_Bright", 0.08);
                SettingHelper.SaveInToSettings("ReaderPage_NightBright", 0.5);
                SettingHelper.SaveInToSettings("BookReader_NightMode", false);
                App.ReaderPage_Night = false;
                InternalBook.AddInternalBook();
            }
            //
            if (SettingHelper.IsSettings("QQReaderHelp"))
            {
                //加载开屏广告
                this.LoadScreenAd();
            }
            //加载首页的底部广告
            this.LoadHomeBannerAd();
            //
            base.Loaded += this.MainPage_Loaded;
            //
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!SettingHelper.IsSettings("QQReaderHelp"))
            {
                SettingHelper.SaveInToSettings("QQReaderHelp", true);
                //this.hc.SetPhoneApplicationPage(this, "MainPage");
                this.hc.SetPhoneApplicationPage(this, "IndexPage");
                this.LayoutRoot.Children.Add(this.hc);
            }

            if (this.piHome == this.pivot.SelectedItem)
            {
                base.ApplicationBar.IsVisible = true;
                this.llsLocalBookshelf.ItemsSource = App.LocalBook.T_LocalBookListViewModel();
            }
            foreach (BookList_M bookListM in App.LocalBook.T_LocalBookListViewModel())
            {
                if (bookListM.str_Id_M != App.ReaderFileName)
                {
                    continue;
                }
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
            }
            this.SetReaderHistory();

            //
            if (!this.downloadUpdateTimeBegin)
            {
                this.downloadUpdateTime.Tick += ((object s, EventArgs ex) =>
                {
                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        App.DownloadList.BeginDownload();
                        App.DownloadList.DownloadImage();
                    }
                });
                this.downloadUpdateTime.Start();
                this.downloadUpdateTime.Interval = TimeSpan.FromMilliseconds(1200);
                this.downloadUpdateTimeBegin = true;
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    //this.CheckUpdate();
                }
                else
                {
                    Prompt.PromptMessage("提示：当前无可用网络！");
                }
            }
            App.QQReader_prePageId = App.QQReader_pageId;
            App.QQReader_pageId = "QQReader_MainPage";
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                this.TodayRecommended();
            }
        }

        /// <summary>
        /// 添加标题至PivotItem
        /// <para>因为代码中的多个PivotItem只能包含一个phone:PivotItem.Header控件</para>
        /// </summary>
        private void AddHeaderToPivotItem()
        {
            //<TextBlock Margin="-20,-15,0,0" Foreground="#c1dc23" FontSize="60" Text="详细信息"/>
            this.piHome.Header = new PivotItemHelper().CreateTextBlock("首页");
            this.piBookStore.Header = new PivotItemHelper().CreateTextBlock("书架");
            this.piRank.Header = new PivotItemHelper().CreateTextBlock("排行");
            this.piCategory.Header = new PivotItemHelper().CreateTextBlock("分类");
            //
            //this.piSetting.Header = new PivotItemHelper().CreateTextBlock("书城");            
            //this.piSearch.Header = new PivotItemHelper().CreateTextBlock("搜索");
        }


        private void ApplicationBarIconButton_About(object sender, EventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EAboutPage, "");
        }

        private void ApplicationBarIconButton_Feedback(object sender, EventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EFeedbackPage, "");
        }

        //private void bookListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    ListBox listBox = sender as ListBox;
        //    if (listBox.SelectedIndex >= 0 && 2 == App.LocalBook.T_LocalBookList_VM1()[listBox.SelectedIndex].int_IsDownload_M)
        //    {
        //        NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", App.LocalBook.T_LocalBookList_VM1()[listBox.SelectedIndex].str_Id_M));
        //        SaveReaderHistory.Delete(App.LocalBook.T_LocalBookList_VM1()[listBox.SelectedIndex]);
        //        SaveReaderHistory.Save(App.LocalBook.T_LocalBookList_VM1()[listBox.SelectedIndex]);
        //        SettingHelper.SaveInToSettings("ReaderPageBack", true);
        //    }
        //    listBox.SelectedIndex = -1;
        //}

        //private void bookListBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    ListBox listBox = sender as ListBox;
        //    if (listBox.SelectedIndex >= 0 && 2 == App.LocalBook.T_LocalBookList_VM2()[listBox.SelectedIndex].int_IsDownload_M)
        //    {
        //        NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", App.LocalBook.T_LocalBookList_VM2()[listBox.SelectedIndex].str_Id_M));
        //        SaveReaderHistory.Delete(App.LocalBook.T_LocalBookList_VM2()[listBox.SelectedIndex]);
        //        SaveReaderHistory.Save(App.LocalBook.T_LocalBookList_VM2()[listBox.SelectedIndex]);
        //        SettingHelper.SaveInToSettings("ReaderPageBack", true);
        //    }
        //    listBox.SelectedIndex = -1;
        //}

        public void CheckUpdate()
        {
            Dictionary<string, string> strs = new Dictionary<string, string>();
            WebHeaderCollection webHeaderCollections = new WebHeaderCollection();
            if (SettingHelper.IsSettings("QQReader_sid"))
            {
                webHeaderCollections["sid"] = SettingHelper.GetValueFromSettings("QQReader_sid") as string;
            }
            webHeaderCollections["c_version"] = "qqreader_1.0.0_0001_wp7";
            webHeaderCollections["ua"] = DeviceExtendedProperties.GetValue("DeviceName").ToString();
            webHeaderCollections["c_platform"] = "wp7";
            HttpPostClient httpPostClient = new HttpPostClient(strs, webHeaderCollections);
            httpPostClient.DownloadStringAsync(new Uri("http://allreader.3g.qq.com/checkupdate", UriKind.Absolute));
            httpPostClient.DownloadStringCompleted += this.CheckUpdate_DownloadStringCompleted;
        }

        private void CheckUpdate_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            base.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result == null)
                {
                    return;
                }
                UpdateJsonData updateJsonDatum = new UpdateJsonData();
                updateJsonDatum = ParseJson.Parse<UpdateJsonData>(e.Result);
                if (updateJsonDatum.update_code == "0")
                {
                    return;
                }
                if (updateJsonDatum.update_code == "2")
                {
                    if (MessageBoxResult.OK == MessageBox.Show("发现新版本，是否升级？", "版本更新", MessageBoxButton.OKCancel))
                    {
                        WebBrowserTask webBrowserTask = new WebBrowserTask();
                        webBrowserTask.Uri = (new Uri(updateJsonDatum.update_url));
                        webBrowserTask.Show();
                        return;
                    }
                }
                else if (updateJsonDatum.update_code == "1" && MessageBoxResult.OK == MessageBox.Show("发现新版本，您需要对版本进行升级!", "版本更新", MessageBoxButton.OK))
                {
                    WebBrowserTask webBrowserTask1 = new WebBrowserTask();
                    webBrowserTask1.Uri = (new Uri(updateJsonDatum.update_url));
                    webBrowserTask1.Show();
                    this.Exit();
                }
            });
        }

        private void Exit()
        {
            while (base.NavigationService.BackStack.Any<JournalEntry>())
            {
                base.NavigationService.RemoveBackEntry();
            }
            base.OnBackKeyPress(new CancelEventArgs());
        }

        private void HomeBookList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }


        //private void localBookListBox_Delete1(object sender, RoutedEventArgs e)
        //{
        //    BookList_M dataContext = (sender as MenuItem).DataContext as BookList_M;
        //    this.localBookListBox_DeleteDownload(dataContext);
        //    this.localBookSource_Delete(dataContext);
        //    App.LocalBook.DeleteBookList1(dataContext);
        //}

        //private void localBookListBox_Delete2(object sender, RoutedEventArgs e)
        //{
        //    BookList_M dataContext = (sender as MenuItem).DataContext as BookList_M;
        //    this.localBookListBox_DeleteDownload(dataContext);
        //    this.localBookSource_Delete(dataContext);
        //    App.LocalBook.DeleteBookList2(dataContext);
        //}

        private void localBookListBox_DeleteDownload(BookList_M m)
        {
            if (App.DownloadList.IsDownloadList(m.str_Id_M))
            {
                if (m.int_IsDownload_M == 0)
                {
                    App.DownloadList.DeleteDownloadList(m.str_DownUrl_M, m.str_Id_M);
                    return;
                }
                if (m.int_IsDownload_M == 1)
                {
                    App.DownloadList.DeleteDownloadClient();
                }
            }
        }

        private void localBookSource_Delete(BookList_M blm)
        {
            if (App.QQReader_StorageFile.IsFile(blm.str_Id_M))
            {
                App.QQReader_StorageFile.DeleteFile(blm.str_Id_M);
            }
            if (App.QQReader_StorageFile.IsFile(string.Concat(blm.str_Id_M, "chapterList")))
            {
                App.QQReader_StorageFile.DeleteFile(string.Concat(blm.str_Id_M, "chapterList"));
            }
            if (SettingHelper.IsSettings(blm.str_Id_M))
            {
                SettingHelper.DeleteSettings(blm.str_Id_M);
            }
            if (SettingHelper.IsSettings(string.Concat(blm.str_Id_M, "markerList")))
            {
                SettingHelper.DeleteSettings(string.Concat(blm.str_Id_M, "markerList"));
            }
            if (SettingHelper.IsSettings(string.Concat(blm.str_Id_M, "CurrentReaderBook")))
            {
                SettingHelper.DeleteSettings(string.Concat(blm.str_Id_M, "CurrentReaderBook"));
            }
            SaveReaderHistory.Delete(blm);
            GetNowTime.DeleteIsostore(blm.str_Cover_M);
            this.SetReaderHistory();
            ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault<ShellTile>((ShellTile x) => x.NavigationUri.ToString().Contains(blm.str_Id_M));
            if (shellTile != null)
            {
                shellTile.Delete();
            }
        }



        private void MenuItem_Loaded1(object sender, RoutedEventArgs e)
        {
            //this.menuChanged = true;
        }

        private void MenuItem_Loaded2(object sender, RoutedEventArgs e)
        {
            //this.menuChanged = true;
        }

        private void MenuItem_Unloaded1(object sender, RoutedEventArgs e)
        {
            //this.menuChanged = false;
        }

        private void MenuItem_Unloaded2(object sender, RoutedEventArgs e)
        {
            //this.menuChanged = false;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.RemoveHelp();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void PhoneApplicationPageBackKeyPress(object sender, CancelEventArgs e)
        {
            try
            {
                //if (this.menuChanged)
                //{
                //    this.menuChanged = false;
                //}
                //else 
                if (MessageBoxResult.Cancel != MessageBox.Show("确定要退出吗？", string.Empty, MessageBoxButton.OKCancel))
                {
                    this.downloadUpdateTime.Stop();
                    App.DownloadList.RemoveTemporaryProgress();
                    this.Exit();
                }
                else
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch
            {
                e.Cancel = true;
            }
        }





        private void ListBoxItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (SettingHelper.IsSettings("ReaderHistory2"))
            {
                BookList_M bookListM = new BookList_M();
                bookListM = SettingHelper.GetValueFromSettings("ReaderHistory2") as BookList_M;
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", bookListM.str_Id_M));
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }

        private void ListBoxItem_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (SettingHelper.IsSettings("ReaderHistory3"))
            {
                BookList_M bookListM = new BookList_M();
                bookListM = SettingHelper.GetValueFromSettings("ReaderHistory3") as BookList_M;
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", bookListM.str_Id_M));
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }

        private void ListBoxItem_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.Today_ErrorImage.Visibility != Visibility.Visible && this.TodayRecommended_M.str_Id_M != "")
            {
                SettingHelper.SaveInToSettings("BookDetail", this.TodayRecommended_M);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
        }

        private void RecommendPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EBookRecommendPage, "");
        }

        private void RankPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //NaviService.Navigate(QQReaderPage.EBookRankPage, "");
            NaviService.Navigate(QQReaderPage.EBookSearchRankPage, "");
        }

        private void SearchPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EBookSearchPage, "");
        }

        private void TypePage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NaviService.Navigate(QQReaderPage.EBookTypePage, "");
        }

        public void RemoveHelp()
        {
            if (this.LayoutRoot.Children.IndexOf(this.hc) >= 0)
            {
                this.LayoutRoot.Children.Remove(this.hc);
            }
        }

        #region 首页：最近阅读
        private void SetReaderHistory()
        {
            //阅读历史：大图
            if (!SettingHelper.IsSettings("ReaderHistory1"))
            {
                EmptyBook(this.lstItemReaderHistoryBig_CoverNULL, this.lstItemReaderHistoryBig_Cover, this.lstItemReaderHistoryBig_Title, this.lstItemReaderHistoryBig_Progress, this.lstItemReaderHistoryBig_Author);
                return;
            }


            BookList_M bookListM = new BookList_M();
            bookListM = SettingHelper.GetValueFromSettings("ReaderHistory1") as BookList_M;
            this.lstItemReaderHistoryBig_Cover.Visibility = Visibility.Visible;
            this.lstItemReaderHistoryBig_CoverNULL.Visibility = Visibility.Collapsed;
            this.lstItemReaderHistoryBig_Cover.Source = new BitmapImage(new Uri(bookListM.str_Cover_M, (InternalBook.IsInternalBook(bookListM.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
            this.lstItemReaderHistoryBig_Title.Text = bookListM.str_Title_M;
            this.lstItemReaderHistoryBig_Author.Text = bookListM.str_Author_M;
            if (SettingHelper.IsSettings(string.Concat(bookListM.str_Id_M, "CurrentReaderBook")))
            {
                LocalBookProgressList_M valueFromSettings = SettingHelper.GetValueFromSettings(string.Concat(bookListM.str_Id_M, "CurrentReaderBook")) as LocalBookProgressList_M;
                this.lstItemReaderHistoryBig_Progress.Text = GetNowTime.SetPercentageText(valueFromSettings.double_ReaderProgress_M);
            }
            //阅读历史：小图左
            if (!SettingHelper.IsSettings("ReaderHistory2"))
            {
                EmptyBook(this.lstHomeReadHistorySamllLeft_CoverNULL, this.lstHomeReadHistorySamllLeft_Cover, this.lstHomeReadHistorySamllLeft_Title, this.lstHomeReadHistorySamllLeft_Progress);
                return;
            }
            BookList_M bookListSettings2 = new BookList_M();
            this.lstHomeReadHistorySamllLeft_Cover.Visibility = Visibility.Visible;
            this.lstHomeReadHistorySamllLeft_CoverNULL.Visibility = Visibility.Collapsed;
            bookListSettings2 = SettingHelper.GetValueFromSettings("ReaderHistory2") as BookList_M;
            this.lstHomeReadHistorySamllLeft_Cover.Source = new BitmapImage(new Uri(bookListSettings2.str_Cover_M, (InternalBook.IsInternalBook(bookListSettings2.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
            this.lstHomeReadHistorySamllLeft_Title.Text = bookListSettings2.str_Title_M;
            if (SettingHelper.IsSettings(string.Concat(bookListSettings2.str_Id_M, "CurrentReaderBook")))
            {
                LocalBookProgressList_M localBookProgressListM2 = SettingHelper.GetValueFromSettings(string.Concat(bookListSettings2.str_Id_M, "CurrentReaderBook")) as LocalBookProgressList_M;
                this.lstHomeReadHistorySamllLeft_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM2.double_ReaderProgress_M);
            }
            //阅读历史：小图中
            if (!SettingHelper.IsSettings("ReaderHistory3"))
            {
                EmptyBook(this.lstHomeReadHistorySamllMiddle_CoverNULL, this.lstHomeReadHistorySamllMiddle_Cover, this.lstHomeReadHistorySamllMiddle_Title, this.lstHomeReadHistorySamllMiddle_Progress);
                return;
            }
            BookList_M bookListSettings3 = new BookList_M();
            this.lstHomeReadHistorySamllMiddle_Cover.Visibility = Visibility.Visible;
            this.lstHomeReadHistorySamllMiddle_CoverNULL.Visibility = Visibility.Collapsed;
            bookListSettings3 = SettingHelper.GetValueFromSettings("ReaderHistory3") as BookList_M;
            this.lstHomeReadHistorySamllMiddle_Cover.Source = new BitmapImage(new Uri(bookListSettings3.str_Cover_M, (InternalBook.IsInternalBook(bookListSettings3.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
            this.lstHomeReadHistorySamllMiddle_Title.Text = bookListSettings3.str_Title_M;
            if (SettingHelper.IsSettings(string.Concat(bookListSettings3.str_Id_M, "CurrentReaderBook")))
            {
                LocalBookProgressList_M localBookProgressListM3 = SettingHelper.GetValueFromSettings(string.Concat(bookListSettings3.str_Id_M, "CurrentReaderBook")) as LocalBookProgressList_M;
                this.lstHomeReadHistorySamllMiddle_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM3.double_ReaderProgress_M);
            }
            //阅读历史：小图小右
            if (!SettingHelper.IsSettings("ReaderHistory4"))
            {
                EmptyBook(this.lstHomeReadHistorySamllRight_CoverNULL, this.lstHomeReadHistorySamllRight_Cover, this.lstHomeReadHistorySamllRight_Title, this.lstHomeReadHistorySamllRight_Progress);
                return;
            }
            BookList_M bookListSettings4 = new BookList_M();
            this.lstHomeReadHistorySamllRight_Cover.Visibility = Visibility.Visible;
            this.lstHomeReadHistorySamllRight_CoverNULL.Visibility = Visibility.Collapsed;
            bookListSettings4 = SettingHelper.GetValueFromSettings("ReaderHistory4") as BookList_M;
            this.lstHomeReadHistorySamllRight_Cover.Source = new BitmapImage(new Uri(bookListSettings4.str_Cover_M, (InternalBook.IsInternalBook(bookListSettings4.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
            this.lstHomeReadHistorySamllRight_Title.Text = bookListSettings4.str_Title_M;
            if (SettingHelper.IsSettings(string.Concat(bookListSettings4.str_Id_M, "CurrentReaderBook")))
            {
                LocalBookProgressList_M localBookProgressListM4 = SettingHelper.GetValueFromSettings(string.Concat(bookListSettings4.str_Id_M, "CurrentReaderBook")) as LocalBookProgressList_M;
                this.lstHomeReadHistorySamllRight_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM4.double_ReaderProgress_M);
            }
        }

        private void EmptyBook(Image imageCoverNull, Image imageCover, TextBlock title, TextBlock progress, TextBlock author = null)
        {
            imageCoverNull.Visibility = Visibility.Visible;
            imageCover.Visibility = System.Windows.Visibility.Collapsed;
            title.Text = "暂无记录";
            progress.Text = string.Empty;
            if (author != null)
                author.Text = string.Empty;
        }

        private void lstItemReaderHistoryBig_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.HomeReadHistory_Tap("ReaderHistory1");
        }

        private void lstHomeReadHistorySamllLeft_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.HomeReadHistory_Tap("ReaderHistory2");
        }

        private void lstHomeReadHistorySamllMiddle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.HomeReadHistory_Tap("ReaderHistory3");
        }

        private void lstHomeReadHistorySamllRight_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.HomeReadHistory_Tap("ReaderHistory4");
        }

        void HomeReadHistory_Tap(string key)
        {
            if (SettingHelper.IsSettings(key))
            {
                BookList_M bookListM = new BookList_M();
                bookListM = SettingHelper.GetValueFromSettings(key) as BookList_M;
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", bookListM.str_Id_M));
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }
        #endregion 首页：最近阅读



        private void SetTodayRecommended(JsonData jd)
        {
            foreach (BookListJsonData bookListJsonDatum in jd.@value.record)
            {
                this.TodayRecommended_M.str_Author_M = string.Concat("作者：", bookListJsonDatum.author);
                this.TodayRecommended_M.str_Category_M = bookListJsonDatum.category;
                this.TodayRecommended_M.str_CategoryName_M = string.Concat("分类：", bookListJsonDatum.categoryName);
                this.TodayRecommended_M.str_Cover_M = bookListJsonDatum.cover;
                this.TodayRecommended_M.str_DownUrl_M = bookListJsonDatum.downUrl;
                this.TodayRecommended_M.str_Finished_M = bookListJsonDatum.finished;
                this.TodayRecommended_M.str_Free_M = bookListJsonDatum.free;
                this.TodayRecommended_M.str_HotValue_M = bookListJsonDatum.hotValue;
                this.TodayRecommended_M.str_Size_M = string.Concat("大小：", bookListJsonDatum.size, "KB");
                this.TodayRecommended_M.str_Id_M = bookListJsonDatum.id;
                this.TodayRecommended_M.str_Intro_M = bookListJsonDatum.intro;
                this.TodayRecommended_M.str_Title_M = bookListJsonDatum.title;
                this.TodayRecommended_M.str_TotalWords_M = bookListJsonDatum.totalWords;
                this.TodayRecommended_M.str_Type_M = bookListJsonDatum.type;
                this.TodayRecommended_M.str_Copyright_M = bookListJsonDatum.copyright;
            }
            this.Today_ErrorImage.Visibility = Visibility.Collapsed;
            this.Today_Title.Text = this.TodayRecommended_M.str_Title_M;
            this.Today_Intro.Text = string.Concat("\u3000\u3000", this.TodayRecommended_M.str_Intro_M.Replace("\r\n", " "));
        }

        private void TodayRecommended()
        {
            if (this.Today_ErrorImage.Visibility == Visibility.Visible)
            {
                Dictionary<string, string> strs = new Dictionary<string, string>()
                {
                    { "fromWho", "4" }
                };
                HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
                httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/book/index", UriKind.Absolute));
                httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.todayRecommended_DownloadStringCompleted);
            }
        }

        private void todayRecommended_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            base.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result == null)
                {
                    return;
                }
                JsonData jsonDatum = new JsonData();
                jsonDatum = ParseJson.Parse<JsonData>(e.Result);
                this.SetTodayRecommended(jsonDatum);
            });
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            base.Focus();
            if (base.ApplicationBar != null)
            {
                //if (this.pivot.SelectedIndex != 0)
                if (this.piHome != this.pivot.SelectedItem)
                {
                    base.ApplicationBar.IsVisible = false;
                }
                else
                {
                    base.ApplicationBar.IsVisible = true;
                }
            }
            if (this.piRank == this.pivot.SelectedItem)
            {
                System.Threading.Tasks.Task.Run(() =>
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        this.txtCacheSize.Text = string.Format("共有 '{0}' 可清除的缓存数据！", this.GetCacheSize());
                    });
                });

            }
        }

        private void llsLocalBookshelf_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            BookList_M model = this.llsLocalBookshelf.SelectedItem as BookList_M;
            if (model != null && model.int_IsDownload_M == 2)
            {
                NaviService.Navigate(QQReaderPage.EBookReaderPage, string.Concat("?FileName=", model.str_Id_M));
                SaveReaderHistory.Delete(model);
                SaveReaderHistory.Save(model);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }

        private void llsLocalBookshelf_Loaded(object sender, RoutedEventArgs e)
        {
            //this.menuChanged = true;
        }

        private void llsLocalBookshelf_Unloaded(object sender, RoutedEventArgs e)
        {
            //this.menuChanged = false;
        }

        private void llsLocalBookshelf_Remove(object sender, RoutedEventArgs e)
        {
            BookList_M dataContext = (sender as MenuItem).DataContext as BookList_M;
            this.localBookListBox_DeleteDownload(dataContext);
            this.localBookSource_Delete(dataContext);
            App.LocalBook.DeleteBookList(dataContext);
        }




        #region 搜索分类
        //private OriginalCategoryList_VM ocl_vm = new OriginalCategoryList_VM();
        //private PublishingCategoryList_VM pcl_vm = new PublishingCategoryList_VM();

        private CategoryList_VM categoryListVM = new CategoryList_VM();
        private void llsSearchCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            BookCategoryList_M item = this.llsSearchCategory.SelectedItem as BookCategoryList_M;
            if (item != null)
            {
                string str = string.Concat("?Category=", item.str_CategoryId_M, "&CategoryName=", item.str_CategoryName_M);
                NaviService.Navigate(QQReaderPage.EBookCityListPage, str);
            }
        }
        #endregion 搜索分类

        private void MarketplaceReview_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                //创建一个查看本应用程序简介和评论的任务
                MarketplaceReviewTask mdr = new MarketplaceReviewTask();
                mdr.Show();
            }
            catch
            {
                Prompt.PromptMessage("未找到评价入口，麻烦在应用列表中长按进行操作！");
            }
        }

        private void MarketplaceDetail_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                //创建一个查看本应用程序简介和评论的任务
                MarketplaceDetailTask task = new MarketplaceDetailTask();
                task.Show();
            }
            catch
            {
                Prompt.PromptMessage("未找到更新数据！");
            }
        }

        private void ImportPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //NaviService.Navigate(QQReaderPage.EBookImportPage, "");
            NaviService.Navigate(QQReaderPage.EBookIntoPage, "");
        }



        #region ******************************广告******************************
        /// <summary>
        /// 加载开屏广告
        /// </summary>
        private void LoadScreenAd()
        {
            this.adHomeScreen.OnApplicationAuthEvent += adHomeScreen_OnApplicationAuthEvent;
            this.adHomeScreen.OnAdRequest += adHomeScreen_OnAdRequest;
            this.adHomeScreen.OnAdRequestFailed += adHomeScreen_OnAdRequestFailed;
            this.adHomeScreen.OnAdRequestLoaded += adHomeScreen_OnAdRequestLoaded;
            this.adHomeScreen.OnShowAdScreen += adHomeScreen_OnShowAdScreen;
            this.adHomeScreen.OnDismissAdScreen += adHomeScreen_OnDismissAdScreen;
            this.adHomeScreen.OnCloseAd += adHomeScreen_OnCloseAd;
            this.adHomeScreen.InitAdControl(AdModeType.Normal);
        }

        private void LoadHomeBannerAd()
        {
            this.adHomeBanner.OnApplicationAuthEvent += adHome_OnApplicationAuthEvent;
            this.adHomeBanner.OnAdRequest += adHome_OnAdRequest;
            this.adHomeBanner.OnAdRequestFailed += adHome_OnAdRequestFailed;
            this.adHomeBanner.OnAdRequestLoaded += adHome_OnAdRequestLoaded;
            this.adHomeBanner.OnShowAdScreen += adHome_OnShowAdScreen;
            this.adHomeBanner.OnDismissAdScreen += adHome_OnDismissAdScreen;
            this.adHomeBanner.OnCloseAd += adHome_OnCloseAd;
            this.adHomeBanner.InitAdControl(AdModeType.Normal);
        }
        #region ********************ScreenAd********************
        void adHomeScreen_OnCloseAd(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnDismissAdScreen(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnShowAdScreen(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnApplicationAuthEvent(object sender, string message)
        {
            LogHelper.LogInfo(message.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnAdRequestLoaded(object sender, EventArgs e)
        {
            UmengSDK.UmengAnalytics.TrackEvent(string.Concat(this.adHomeScreen.AdPosition, MethodBase.GetCurrentMethod().Name));
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnAdRequestFailed(object sender, SurfaceAdEventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnAdRequest(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }
        #endregion ********************ScreenAd********************

        #region ********************BannerAd********************
        void adHome_OnCloseAd(object sender, EventArgs e)
        {
            UmengSDK.UmengAnalytics.TrackEvent(string.Concat(this.adHomeBanner.AdPosition, MethodBase.GetCurrentMethod().Name));
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnDismissAdScreen(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnShowAdScreen(object sender, EventArgs e)
        {
            UmengSDK.UmengAnalytics.TrackEvent(string.Concat(this.adHomeBanner.AdPosition, MethodBase.GetCurrentMethod().Name));
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnApplicationAuthEvent(object sender, string message)
        {
            LogHelper.LogInfo(message.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnAdRequestLoaded(object sender, EventArgs e)
        {
            UmengSDK.UmengAnalytics.TrackEvent(string.Concat(this.adHomeBanner.AdPosition, MethodBase.GetCurrentMethod().Name));
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnAdRequestFailed(object sender, SurfaceAdEventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnAdRequest(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }
        #endregion ********************BannerAd********************
        #endregion ******************************广告******************************

        #region ******************************缓存清理******************************
        private void CacheClearPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //按目录列出缓存信息，进行清理
            //this.NavigationService.Navigate(new Uri("/Pages/CacheClearPage.xaml",UriKind.Relative));
            System.Threading.Tasks.Task.Run(() =>
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        this.ClearCacheContent();
                        this.txtCacheSize.Text = string.Format("共有 '{0}' 可清除的缓存数据！", this.GetCacheSize());
                    });
                });

        }

        string GetCacheSize()
        {
            double cacheSize = 0;
            IsolatedStorageFile isolatedStorageFile = null;
            try
            {
                //根目录下的文件，包含下载的文件和电脑配置文件
                using (isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var rootfiles = isolatedStorageFile.GetFileNames();
                    if (rootfiles != null && rootfiles.Length > 0)
                    {
                        //这是远程配置缓存文件
                        rootfiles = (from p in rootfiles where !p.Equals("__ApplicationSettings") && !p.ToLower().EndsWith(".tmp") && !p.EndsWith("chapterList") select p).ToArray<string>();
                        if (rootfiles != null && rootfiles.Length > 0)
                        {
                            foreach (string rootfile in rootfiles)
                            {
                                if (!isolatedStorageFile.FileExists(rootfile))
                                    continue;
                                try
                                {
                                    using (IsolatedStorageFileStream stream = isolatedStorageFile.OpenFile(rootfile, FileMode.Open, FileAccess.Read))
                                    {
                                        cacheSize += stream.Length;//返回大B
                                        stream.Close();
                                        stream.Dispose();
                                    }
                                }
                                catch { }
                            }
                        }
                    }
                    //通过电脑连接的文件
                    var contentFiles = isolatedStorageFile.GetFileNames(Path.Combine("content", "*"));
                    if (contentFiles != null && contentFiles.Length > 0)
                    {
                        foreach (string contentFile in contentFiles)
                        {
                            if (!isolatedStorageFile.FileExists(Path.Combine("content", contentFile)))
                                continue;
                            try
                            {
                                using (IsolatedStorageFileStream stream = isolatedStorageFile.OpenFile(Path.Combine("content", contentFile), FileMode.Open, FileAccess.Read))
                                {
                                    cacheSize += stream.Length;//返回大B
                                    stream.Close();
                                    stream.Dispose();
                                }
                            }
                            catch { }
                        }
                    }
                    //
                }
            }
            catch
            { }
            finally
            {
                if (isolatedStorageFile != null)
                {
                    isolatedStorageFile.Dispose();
                    isolatedStorageFile = null;
                }
            }

            if (cacheSize > 0)
            {
                if (cacheSize / 1024 / 1024 > 1)
                {
                    return string.Concat(Math.Round((cacheSize / 1024.00) / 1024.00, 2), " MB");
                }
                else if (cacheSize / 1024 > 1)
                {
                    return string.Concat(Math.Round((cacheSize / 1024.00), 2), " KB");
                }
                else
                {
                    return string.Concat(cacheSize, " B");
                }

            }

            return "0 B";
        }

        void ClearCacheContent()
        {
            IsolatedStorageFile isolatedStorageFile = null;
            try
            {
                //根目录下的文件，包含下载的文件和电脑配置文件
                using (isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var rootfiles = isolatedStorageFile.GetFileNames();
                    if (rootfiles != null && rootfiles.Length > 0)
                    {
                        //这是远程配置缓存文件
                        rootfiles = (from p in rootfiles where !p.Equals("__ApplicationSettings") && !p.ToLower().EndsWith(".tmp") && !p.EndsWith("chapterList") select p).ToArray<string>();
                        if (rootfiles != null && rootfiles.Length > 0)
                        {
                            foreach (string rootfile in rootfiles)
                            {
                                if (!isolatedStorageFile.FileExists(rootfile))
                                    continue;
                                try
                                {
                                    isolatedStorageFile.DeleteFile(rootfile);
                                }
                                catch { }
                            }
                        }
                    }
                    //通过电脑连接的文件
                    var contentFiles = isolatedStorageFile.GetFileNames(Path.Combine("content", "*"));
                    if (contentFiles != null && contentFiles.Length > 0)
                    {
                        foreach (string contentFile in contentFiles)
                        {
                            if (!isolatedStorageFile.FileExists(Path.Combine("content", contentFile)))
                                continue;
                            try
                            {
                                isolatedStorageFile.DeleteFile(Path.Combine("content", contentFile));
                            }
                            catch { }
                        }
                    }
                    //
                }
            }
            catch
            { }
            finally
            {
                if (isolatedStorageFile != null)
                {
                    isolatedStorageFile.Dispose();
                    isolatedStorageFile = null;
                }
            }
        }
        #endregion ******************************缓存清理******************************

        private void AdMoney_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (MessageBoxResult.OK == MessageBox.Show("正在开发此功能，根据您的广告点击次数，每月会为您结算一次！您说此功能如何，点击确定进行进行反馈，多谢！", AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
            {
                NaviService.Navigate(QQReaderPage.EFeedbackPage, "");
            }
        }












    }
}